package com.dq.service.record.impl;

import com.dq.controller.api.merchant.in.query.RoyalRecordQuery;
import com.dq.domain.org.Org;
import com.dq.domain.record.RoyaltyRecord;
import com.dq.repository.AllRepository;
import com.dq.service.record.RoyaltyRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @author liuhui
 * @date 2019/11/28 0028 14:26:11
 */
@Service
public class RoyaltyRecordServiceImpl extends AllRepository implements RoyaltyRecordService {

    @PersistenceContext
    private EntityManager entityManager;


    @Override
    public List<RoyaltyRecord> findByWhere(RoyalRecordQuery royalRecordQuery, Org org) {
        StringBuilder hql = new StringBuilder("select u from RoyaltyRecord u where u.deleted=false");
        Query q = createWhereHql(royalRecordQuery,org,hql);
        q.setFirstResult((royalRecordQuery.getPage()-1)*royalRecordQuery.getSize());
        q.setMaxResults(royalRecordQuery.getSize());
        List<RoyaltyRecord> royaltyRecordList = q.getResultList();
        return royaltyRecordList;
    }

    @Override
    public Long countByWhere(RoyalRecordQuery royalRecordQuery, Org org) {
        StringBuilder hql = new StringBuilder("select count(u) from RoyaltyRecord u where u.deleted=false");
        Query q = createWhereHql(royalRecordQuery,org,hql);
        return new Long((long) q.getResultList().get(0));
    }

    public Query createWhereHql(RoyalRecordQuery royalRecordQuery, Org org,StringBuilder hql){
        hql.append(" and u.org =:org");
        if(null!=royalRecordQuery.getBeginTime()){
            hql.append(" and u.createTime >=:beginTime");
        }
        if(null!=royalRecordQuery.getEndTime()){
            hql.append(" and u.createTime <=:endTime");
        }
        if(StringUtils.isNotEmpty(royalRecordQuery.getValue())){
            hql.append(" and (u.orders.ordersNo like:value");
            hql.append(" or u.sysUser.userRealcName like:value)");
        }
        hql.append(" ORDER BY u.createTime desc");
        Query query = entityManager.createQuery(hql.toString());
        query.setParameter("org",org);
        if(null!=royalRecordQuery.getBeginTime()){
            query.setParameter("beginTime",royalRecordQuery.getBeginTime());
        }
        if(null!=royalRecordQuery.getEndTime()){
            query.setParameter("endTime",royalRecordQuery.getEndTime());
        }
        if(StringUtils.isNotEmpty(royalRecordQuery.getValue())){
            query.setParameter("value","%"+royalRecordQuery.getValue()+"%");
        }
        return query;
    }
}
